﻿using ConsoleAutoHomeBBS.AutoHome.Models;
using ConsoleAutoHomeBBS.Common;
using Dapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace ConsoleAutoHomeBBS.AutoHome.Actions
{
    /*----------------------------------------------------------------
    * 创 建 人 ：朱雪松
    * 创建时间 ：2020/10/13 11:37:53
    * 修 改 人 ：
    * 修改时间 ：
    * 版 本 号 ：@version 1.0
    * 描    述 ：
    *******************************************************************/

    public class ExecuteCommand
    {
        IDbConnection connection;
        public ExecuteCommand()
        {
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionAutoHomeStr"].ToString());
        }

        public void Run()
        {
            // https://club.autohome.com.cn/frontapi/bbs/getSeriesByLetter?firstLetter=
            //GetBBSBrand("https://club.autohome.com.cn/frontapi/bbs/getSeriesByLetter");

            //获取论坛下的主题列表
            GetTopPic();
        }


        /// <summary>
        /// 抓取所有论坛编号及品牌论坛信息，插入数据库中
        /// </summary>
        /// <param name="url"></param>
        private void GetBBSBrand(string url)
        {
            var json = Util.GetHtmlWithUtf(url);
            var result = JsonConvert.DeserializeObject<ResultModel<List<BBSLetter>>>(json);

            if (result.returncode == 0)
            {


                foreach (var item in result.result)
                {
                    foreach (var itemBrand in item.bbsBrand)
                    {
                        //查询是否存在，不存在则插入数据库
                        string sqlText = @"SELECT bbsBrandId FROM [dbo].[BBSBrand] WHERE [bbsBrandId]=@bbsBrandId";
                        var query = connection.Query<BBSBrand>(sqlText, new { bbsBrandId = itemBrand.bbsBrandId }).FirstOrDefault();
                        if (query == null)
                        {
                            //插入数据
                            sqlText = "INSERT dbo.BBSBrand VALUES  ( @bbsBrandId , @bbsBrandName, @totalResult , @letter ,GETDATE() , 0 )";
                            connection.ExecuteScalar(sqlText,
                                        new
                                        {
                                            bbsBrandId = itemBrand.bbsBrandId,
                                            bbsBrandName = itemBrand.bbsBrandName,
                                            totalResult = itemBrand.totalResult,
                                            letter = item.letter,
                                        });

                            foreach (var itemBBS in itemBrand.bbsList)
                            {
                                //插入数据
                                sqlText = "INSERT dbo.BBS VALUES  (  @bbsId ,  @bbsName , @totalResult ,  GETDATE() , 0,@bbsBrandId  )";
                                connection.ExecuteScalar(sqlText,
                                            new
                                            {
                                                bbsBrandId = itemBrand.bbsBrandId,
                                                bbsId = itemBBS.bbsId,
                                                bbsName = itemBBS.bbsName,
                                                totalResult = itemBBS.totalResult,
                                            });
                            }
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine(result.message);
            }
        }


        /// <summary>
        /// 获取某品牌论坛列表数据
        /// </summary>
        private void GetTopPic()
        {
            bool isExist = true;
            while (isExist)
            {
                //查询是否存在，不存在则插入数据库
                string sqlText = @"SELECT TOP 1 * FROM dbo.BBS WHERE Status=0";
                var query = connection.Query<BBS>(sqlText).FirstOrDefault();
                if (query != null)
                {
                    #region
                    //更改数据状态，该论坛开始抓取了
                    sqlText = "UPDATE dbo.BBS SET Status=1 WHERE bbsId=@bbsId";
                    connection.ExecuteScalar(sqlText, new { bbsId = query.bbsId });
                    #endregion


                    int pageIndex = 1;
                    int pageCount = 1000;
                    while (pageIndex <= pageCount)
                    {
                        //根据论坛编号和分页索引编号，拼接url，访问指定论坛
                        string bbsUrl = "https://club.autohome.com.cn/frontapi/topics/getByBbsId?pageindex={0}&pagesize=50&bbs=c&bbsid={1}&fields=topicid%2Ctitle%2Cpost_memberid%2Cpost_membername%2Cpostdate%2Cispoll%2Cispic%2Cisrefine%2Creplycount%2Cviewcount%2Cvideoid%2Cisvideo%2Cvideoinfo%2Cqainfo%2Ctags%2Ctopictype%2Cimgs%2Cjximgs%2Curl%2Cpiccount%2Cisjingxuan%2Cissolve%2Cliveid%2Clivecover%2Ctopicimgs&orderby=lastpostdata-";
                        bbsUrl = string.Format(bbsUrl, pageIndex, query.bbsId);
                        var json = Util.GetHtmlWithUtf(bbsUrl);
                        var result = JsonConvert.DeserializeObject<ResultModel<BBSPageList>>(json);

                        pageCount = result.result.pagecount;
                        pageIndex++;

                        if (result.returncode == 0)
                        {

                        }
                        else
                        {
                            Console.WriteLine(result.message + "   " + bbsUrl);
                        }
                    }


                    #region
                    //更改数据状态，该论坛抓取完毕
                    sqlText = "UPDATE dbo.BBS SET Status=2 WHERE bbsId=@bbsId";
                    connection.ExecuteScalar(sqlText, new { bbsId = query.bbsId });
                    #endregion
                }
                else
                {
                    isExist = false;
                    Console.WriteLine("没有论坛可以抓取了！！！！");
                }
            }
        }
    }
}
